package com.flying.flyingchessgame.service.impl;

import com.flying.flyingchessgame.entity.User;
import com.flying.flyingchessgame.mapper.UserMapper;
import com.flying.flyingchessgame.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户服务实现类
 * <p>
 * 实现UserService接口，提供用户相关业务逻辑的具体实现，
 * 包括用户注册、登录、信息查询等功能。
 * </p>
 * 
 * @author flying-chess
 * @version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * {@inheritDoc}
     */
    @Override
    public User saveUser(String username, String password, String email) {
        logger.info("创建新用户: {}", username);
        
        User user = new User();
        user.setUsername(username);
        user.setPassword(encryptPassword(password));
        user.setEmail(email);
        user.setGamesPlayed(0);
        user.setGamesWon(0);
        
        // 使用MyBatis插入用户
        userMapper.insert(user);
        logger.debug("用户已保存: ID={}", user.getId());
        
        return user;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean checkUsernameExists(String username) {
        boolean exists = userMapper.existsByUsername(username);
        logger.debug("检查用户名是否存在: {} - {}", username, exists);
        return exists;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean checkEmailExists(String email) {
        if (email == null || email.isEmpty()) {
            logger.debug("邮箱为空，跳过检查");
            return false;
        }
        boolean exists = userMapper.existsByEmail(email);
        logger.debug("检查邮箱是否存在: {} - {}", email, exists);
        return exists;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String encryptPassword(String password) {
        logger.debug("加密密码");
        return passwordEncoder.encode(password);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public User getUserById(Long id) {
        logger.debug("通过ID查询用户: {}", id);
        return userMapper.findById(id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public User getUserByUsername(String username) {
        logger.debug("通过用户名查询用户: {}", username);
        return userMapper.findByUsername(username);
    }
} 